package com.gin.no_gay_alliance.worker;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.database.dao.ScanTaskDao;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 监控主题工作, 每5分钟执行一次，查询所有监控中的扫描任务，提交扫描工作 {@link WatchingScanWorker}
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/21 14:54
 **/
public class WatchingWorker extends Worker {
    private static final String TAG = WatchingWorker.class.getSimpleName();

    public WatchingWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        ScanTaskDao dao = MyApplication.app.ngaDatabase.scanTaskDao();
        Log.d(TAG, "检查监控任务...");
        // 监控中任务
        List<Integer> watchingIds = dao.listAll().stream().filter(i -> i.watching).map(i -> i.id).collect(Collectors.toList());

        // 提交监控扫描工作
        for (Integer id : watchingIds) {
            WatchingScanWorker.startWorker(id);
        }
        // 启动下一次
        startWorker();
        return Result.success();
    }

    /**
     * 启动工作
     */
    public static void startWorker() {
        //创建工作请求
        WorkRequest workRequest = buildWorkRequest();
        //提交任务
        WorkManager.getInstance(MyApplication.app).enqueue(workRequest);
    }

    /**
     * 创建工作请求
     *
     * @return 工作请求
     */
    public static WorkRequest buildWorkRequest() {
        // 连上网络才执行
        Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();

        return new OneTimeWorkRequest.Builder(WatchingWorker.class)
                .setConstraints(constraints)
                // 延迟5分钟执行
                .setInitialDelay(1, TimeUnit.MINUTES)
                // 重试策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }
}
